package com.aps.apspda.activity;

import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.adapter.EqpThingListAdapter;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.callback.SuccessAndFailCallback;
import com.aps.apspda.dialog.CTsensorFragmentDialog;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.MaterialInfoBean;
import com.aps.apspda.entity.WaferSawEntity;
import com.aps.apspda.myview.ClearEditText;
import com.aps.apspda.myview.TitleView;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class ThingChangeActivity extends BaseActivity {

    @BindView(R.id.topView)
    TitleView topView;
    @BindView(R.id.etRemark)
    EditText etRemark;
    @BindView(R.id.tvEqpId)
    TextView tvEqpId;
    @BindView(R.id.rvEqpList)
    RecyclerView rvEqpList;
    @BindView(R.id.etCapillarySeqNo)
    EditText etCapillarySeqNo;
    @BindView(R.id.etCapillaryMaterialPartNo)
    EditText etCapillaryMaterialPartNo;
    @BindView(R.id.llCapillary)
    LinearLayout llCapillary;
    @BindView(R.id.etBBD)
    ClearEditText etBBD;
    @BindView(R.id.rlBBD)
    RelativeLayout rlBBD;

    private List<MaterialInfoBean> materialinfoBeanList;
    private EqpThingListAdapter eqpThingListAdapter;
    private MaterialInfoBean bean;
    private String type;
    private boolean isAllow = false;
    private boolean isYingYuan = false;
    private boolean isRuanYuan = false;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_thing_change;
    }

    @Override
    protected void initView() {
        topView.setTitle("材料更换(" + StaticMembers.CUR_USER.getUSERNAME() + ")");
        topView.setTitleMode(TitleView.NORMAL_TEXT_MODE);
        topView.setRightListener("确定更换", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShake.check(v.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                if (materialinfoBeanList.size() == 0) {
                    ToastUtils.showFreeToast("请先扫描物料条码",
                            ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                if (type.equals("Capillary")) {
                    if (etCapillarySeqNo.getText().toString().trim().length() != 0 &&
                            etCapillaryMaterialPartNo.getText().toString().trim().length() != 0) {
                        isAllow = true;
                    } else {
                        isAllow = false;
                    }
                }
                if (isAllow) {
                    if (type.equals("HublessBlade") || type.equals("HubBlade")
                            || type.equals("HubBladeYZ1") || type.equals("HubBladeYZ2")) {
                        if (etBBD.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请填写BBD",
                                    ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                    }
                    requestSubmit();
                } else {
                    ToastUtils.showFreeToast("请检查扫描的物料条码是否正确",
                            ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                }
            }
        });
        rvEqpList.setLayoutManager(new LinearLayoutManager(ThingChangeActivity.this));
        rvEqpList.setItemAnimator(new DefaultItemAnimator());
        rvEqpList.addItemDecoration(new DividerItemDecoration(ThingChangeActivity.this, 1));

        bean = (MaterialInfoBean)
                getIntent().getSerializableExtra("mEntity");
        type = bean.getType();

        if (type.equals("Capillary")) {
            llCapillary.setVisibility(View.VISIBLE);
            etRemark.setVisibility(View.GONE);
        } else {
            setCallback(etRemark);
            llCapillary.setVisibility(View.GONE);
            etRemark.setVisibility(View.VISIBLE);
            if (type.equals("HublessBlade") || type.equals("HubBlade")
                    || type.equals("HubBladeYZ1") || type.equals("HubBladeYZ2")) {
                rlBBD.setVisibility(View.VISIBLE);
            } else {
                rlBBD.setVisibility(View.GONE);
            }
        }
        tvEqpId.setText(getEqpID());

        etCapillaryMaterialPartNo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (etCapillarySeqNo.getText().toString().trim().length() != 0) {
                        if (s.length() > etCapillarySeqNo.getText().toString().trim().length()) {
                            ToastUtils.showFreeToast("料号长度应该小于序列号长度，请检查",
                                    ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                    }
                    if (materialinfoBeanList.size() != 0) {
                        materialinfoBeanList.get(0).setMaterialPartNo(s.toString());
                    } else {
                        bean.setMaterialPartNo(s.toString());
                        materialinfoBeanList.add(bean);
                    }
                    eqpThingListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        etCapillarySeqNo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (etCapillaryMaterialPartNo.getText().toString().trim().length() != 0) {
                        if (s.length() < etCapillaryMaterialPartNo.getText().toString().trim().length()) {
                            ToastUtils.showFreeToast("序列号长度应大于料号长度，请检查",
                                    ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                    }
                    if (materialinfoBeanList.size() != 0) {
                        materialinfoBeanList.get(0).setSeqNo(s.toString());
                    } else {
                        bean.setSeqNo(s.toString());
                        materialinfoBeanList.add(bean);
                    }
                    eqpThingListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        etRemark.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });

        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (s.length() > 0) {
                        //扫描到数据 然后请求接口
                        isAllow = isAllow(s.toString());
                        if (type.equals("HubBlade") || type.equals("HubBladeYZ1") || type.equals("HubBladeYZ2")) {
                            if (!isYingYuan) {
                                if (isAllow) {
                                    materialinfoBeanList.clear();
                                    materialinfoBeanList.add(bean);
                                    eqpThingListAdapter.notifyDataSetChanged();
                                    verifyCtsensor();
                                } else {
                                    materialinfoBeanList.clear();
                                    eqpThingListAdapter.notifyDataSetChanged();
                                    ToastUtils.showFreeToast("请检查扫描的物料条码是否正确",
                                            ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                                }
                            }
                        } else if (type.equals("HublessBlade")) {
                            if (!isRuanYuan) {
                                if (isAllow) {
                                    materialinfoBeanList.clear();
                                    materialinfoBeanList.add(bean);
                                    eqpThingListAdapter.notifyDataSetChanged();
                                    verifyCtsensor();
                                } else {
                                    materialinfoBeanList.clear();
                                    eqpThingListAdapter.notifyDataSetChanged();
                                    ToastUtils.showFreeToast("请检查扫描的物料条码是否正确",
                                            ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                                }
                            }
                        } else {
                            if (isAllow) {
                                materialinfoBeanList.clear();
                                materialinfoBeanList.add(bean);
                                eqpThingListAdapter.notifyDataSetChanged();
                            } else {
                                materialinfoBeanList.clear();
                                eqpThingListAdapter.notifyDataSetChanged();
                                ToastUtils.showFreeToast("请检查扫描的物料条码是否正确",
                                        ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                            }
                        }
                    } else {
                        materialinfoBeanList.clear();
                        eqpThingListAdapter.notifyDataSetChanged();
                        ToastUtils.showFreeToast("扫描信息有误", ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void requestSubmit() {
        EntityCallBack<BaseEntity<Object>> callBack = new DialogEntityCallBack<BaseEntity<Object>>
                (new TypeToken<BaseEntity<Object>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<Object>> response) {

                if (response.body().isSuccess(ThingChangeActivity.this)) {
                    //do something
                    ToastUtils.showFreeToast("更换成功",
                            ThingChangeActivity.this, true, Toast.LENGTH_SHORT);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ThingChangeActivity.this.finish();
                        }
                    }, 1000);

                } else {
                    materialinfoBeanList.clear();
                    eqpThingListAdapter.notifyDataSetChanged();
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<Object>> response) {
                super.onError(response);
                loadError(response.getException(), "ChangeMeterial");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EqpId", getEqpID());
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("Name", StaticMembers.CUR_USER.getUSERNAME());
        map.put("Type", bean.getType());
        map.put("Size", bean.getSize());
        map.put("RemainTime", bean.getRemainTime());
        map.put("SeqNo", bean.getSeqNo());
        map.put("MaterialPartNo", bean.getMaterialPartNo());
        map.put("Device", bean.getDevice());
        map.put("WaferSource", bean.getWaferSource());
        map.put("Diagram", bean.getDiagram());
        map.put("ThawEndTime", bean.getThawEndTime());
        map.put("SawLength", bean.getSawLength());
        map.put("SawThickness", bean.getSawThickness());
        map.put("ExternalDiameter", bean.getExternalDiameter());
        map.put("InternalDiameter", bean.getInternalDiameter());
        map.put("MaterialLotNo", bean.getMaterialLotNo());
        map.put("EndTime", bean.getEndTime());
        map.put("StartTime", bean.getStartTime());
        map.put("BBD", etBBD.getText().toString().trim());
        NetUtils.requestNet(this, "/ChangeMeterial", map, callBack);
    }

    public boolean isAllow(String str) {
        if (type.equals("Nozzle") ||
                type.equals("Thimble") || type.equals("StampingPin") || type.equals("DispenseTool")) {
            String[] strs = str.split(";");
            if (strs.length == 2) {
                bean.setSeqNo(strs[0]);
                bean.setMaterialPartNo(strs[1]);
                return true;
            } else {
                return false;
            }
        } else if (type.equals("Leadframe")) {
            String[] strs2 = str.split(";");
            if (strs2.length == 6) {
                bean.setSeqNo(strs2[0]);
                bean.setMaterialPartNo(strs2[2].replace("1P", ""));
                bean.setMaterialLotNo(strs2[3].replace("1T", ""));
                bean.setStartTime(strs2[4].replace("9D", ""));
                return true;
            } else {
                return false;
            }
        } else if (type.equals("Wire")) {
            String[] strs = str.split(";");
            if (strs.length == 3) {
                bean.setSize((strs[0].split(" "))[0]);
                bean.setMaterialPartNo(strs[1]);
                bean.setSeqNo(strs[2]);
                return true;
            } else if (strs.length == 4) {
                bean.setSize((strs[0].split(" "))[0]);
                bean.setMaterialPartNo(strs[1]);
                bean.setSeqNo(strs[2]);
                bean.setRemainTime(strs[3]);
                return true;
            } else {
                return false;
            }
        } else if (type.equals("HublessBlade")) {
            isRuanYuan = false;
            String[] strs;
            if (str.contains(";")) {
                strs = str.split(";");
            } else {
                strs = new String[1];
                strs[0] = str;
            }
            if (strs.length == 5) {
                bean.setMaterialPartNo(strs[0]);
                String str1 = strs[1].replace(" ", "");
                bean.setExternalDiameter(str1.substring(0, str1.length() - 1));
                String str2 = strs[2].replace(" ", "");
                bean.setInternalDiameter(str2.substring(0, str2.length() - 1));
                String str3 = strs[3].replace(" ", "");
                bean.setSawThickness(str3.substring(0, str3.length() - 1));
                bean.setSeqNo(strs[4]);
                return true;
            } else if (strs.length == 1 && strs[0].length() == 15) {
                isRuanYuan = true;
                str = str.substring(0, str.length() - 3);
                requestHubBlade(str);
                return true;
            } else {
                return false;
            }
        } else if (type.equals("Wafer")) {
            String[] strs = str.split("\\^");
            if (strs.length == 4) {
                bean.setDevice(strs[0]);
                bean.setWaferSource(strs[1]);
                bean.setDiagram(strs[2]);
                bean.setMaterialPartNo(strs[3]);
                return true;
            } else {
                return false;
            }
        } else if (type.equals("Epoxy")) {
            String[] strs = str.split(";");
            if (strs.length == 5) {
                bean.setMaterialPartNo(strs[0]);
                bean.setThawEndTime(strs[1]);
                bean.setEndTime(strs[2]);
                bean.setSeqNo(strs[3]);
                return true;
            } else {
                return false;
            }
        } else if (type.equals("Block")) {
            if (str.length() == 2) {
                str = str.replace("0", "");
                if (AppUtils.isNumeric(str)) {
                    bean.setMaterialPartNo(str);
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else if (type.equals("HubBlade") || type.equals("HubBladeYZ1") || type.equals("HubBladeYZ2")) {
            isYingYuan = false;
            String[] strs;
            if (str.contains(";")) {
                strs = str.split(";");
            } else {
                strs = new String[1];
                strs[0] = str;
            }
            if (strs.length == 4) {
                bean.setMaterialPartNo(strs[0]);
                bean.setSawLength(strs[1]);
                bean.setSawThickness(strs[2]);
                bean.setSeqNo(strs[3]);
                return true;
            } else if (strs.length == 5) {
                bean.setMaterialPartNo(strs[0]);
                bean.setSawLength(strs[1]);
                bean.setSawThickness(strs[2]);
                bean.setSeqNo(strs[4]);
                return true;
            } else if (strs.length == 1 && str.length() > 15) {
                if (str.substring(str.length() - 15, str.length() - 14).equals("H")) {
                    isYingYuan = true;
                    str = str.substring(str.length() - 15, str.length() - 3);
                    requestHubBlade(str);
                    return true;
                } else if (str.substring(str.length() - 16, str.length() - 15).equals("H")) {
                    isYingYuan = true;
                    str = str.substring(0, str.length() - 1);
                    str = str.substring(str.length() - 15, str.length() - 3);
                    requestHubBlade(str);
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    private void verifyCtsensor() {
        final CTsensorFragmentDialog cTsensorFragmentDialog = new CTsensorFragmentDialog();
        cTsensorFragmentDialog.setCallBackAndWhere(new SuccessAndFailCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFail() {
                isAllow = false;
                materialinfoBeanList.clear();
                eqpThingListAdapter.notifyDataSetChanged();
            }
        }, bean);
        cTsensorFragmentDialog.show(getSupportFragmentManager(), "cTsensor_dialog");
    }

    private void requestHubBlade(String str) {
        EntityCallBack<BaseEntity<WaferSawEntity>> callBack = new DialogEntityCallBack<BaseEntity<WaferSawEntity>>
                (new TypeToken<BaseEntity<WaferSawEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<WaferSawEntity>> response) {

                if (response.body().isSuccess(ThingChangeActivity.this)) {
                    isAllow = true;
                    bean.setMaterialPartNo(response.body().getData().getMATERIALPARTNO());
                    bean.setSawLength(response.body().getData().getSAWLENGTH());
                    bean.setSawThickness(response.body().getData().getSAWTHICKNESS());
                    bean.setSeqNo(response.body().getData().getSEQNO());
                    bean.setInternalDiameter(response.body().getData().getINTERNALDIAMETER());
                    bean.setExternalDiameter(response.body().getData().getEXTERNALDIAMETER());
                    if (isAllow) {
                        materialinfoBeanList.clear();
                        materialinfoBeanList.add(bean);
                        eqpThingListAdapter.notifyDataSetChanged();
                        verifyCtsensor();
                    } else {
                        materialinfoBeanList.clear();
                        eqpThingListAdapter.notifyDataSetChanged();
                        ToastUtils.showFreeToast("请检查扫描的物料条码是否正确",
                                ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                    }
                } else {
                    isAllow = false;
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            ThingChangeActivity.this, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<WaferSawEntity>> response) {
                super.onError(response);
                isAllow = false;
                loadError(response.getException(), "WaferSaw");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("SeqNo", str);
        map.put("Materialtype", type);
        NetUtils.requestNet(this, "/WaferSaw", map, callBack);
    }

    @Override
    protected void initData() {
        materialinfoBeanList = new ArrayList<>();
        eqpThingListAdapter = new EqpThingListAdapter(materialinfoBeanList, null);
        eqpThingListAdapter.setIsShowButton(false);
        eqpThingListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpThingListAdapter.isFirstOnly(true);
        rvEqpList.setAdapter(eqpThingListAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }
}
